import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;


    public PriorityQueue() {
        this.elem = new int[10];
        this.usedSize = 0;
    }


    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        int len = array.length;
        for (int i = (len - 1 - 1)/2;i >= 0;i--) {
            shiftDown(i,len);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int cur = root*2 + 1;
        while(cur < len) {
            if (cur + 1 < len && elem[cur] < elem[cur + 1]) {
                cur = cur + 1;
            }
            if (elem[root] >= elem[cur]) {
                return;
            } else {
                exchange(cur, root);
            }
            root = cur;
            cur = root * 2 + 1;
        }
    }
    private void exchange(int i,int j){
        int mid;
        mid = elem[i];
        elem[i] = elem[j];
        elem[j] = mid;
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()){
            this.elem = Arrays.copyOf(elem,elem.length*2);
        }
        if(usedSize == 0){
            elem[0] = val;
            usedSize++;
            return;
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child - 1)/2;
        while (child > 0){
            if(elem[parent] > elem[child]) {
                return;
            }else{
                exchange(parent,child);
                child = parent;
                parent = (child - 1)/2;
            }
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        if(isEmpty()){
            return;
        }
        int len = usedSize;
        exchange(0,len - 1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(isEmpty()){
            return -1;
        }
        return elem[0];
    }
//    public int[] smallestK(int[] arr, int k) {
//        PriorityQueue priorityQueue = new PriorityQueue();
//        for (int i = 0; i < k; i++) {
//            priorityQueue.push(arr[k]);
//        }
//        for (int i = k; i < arr.length; i++) {
//            if(arr[k] < priorityQueue.peekHeap()){
//                priorityQueue.pollHeap();
//                priorityQueue.push(arr[k]);
//            }
//        }
//        return priorityQueue.elem;
//    }
}